package com.situ.company.util;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import com.situ.company.department.model.DepartmentModel;

public class FmtRequest {
	
	/**
	 * 第一个name属性值和model字段相同情况
	 * 根据请求参数情况反射到实体类对象中
	 * @param <T>
	 * 需要反射生成
	 * @param req
	 * @param clazz
	 * @return
	 */
	public static <T> T parseModel(HttpServletRequest req,Class<T> clazz) {
		T obj=null;
		try {
			obj=clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		//第一个name属性值和model字段相同
		//第一个是jsp中name属性值，第二个是value值，[]是可能存在复选框
		Map<String,String[]> map=req.getParameterMap();
		for (Entry<String, String[]> entry:map.entrySet()) {
			String name=entry.getKey();
			if("action".equals(name))
				continue;
			try {
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);
				field.set(obj, entry.getValue()[0]);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}
	
	
	/**
	 * 需要自己定义map映射关系
	 * name属性 和model属性名不同的情况
	 * @param <T>
	 * @param req
	 * @param clazz
	 * @param fields
	 * 	第一个String是model属性 第二个String是name字段
	 * @return
	 */
	public static <T> T parseModel(HttpServletRequest req,Class<T> clazz,Map<String,String> fields) {
		T obj=null;
		try {
			obj=clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		for(Entry<String, String> entry:fields.entrySet()) {
			String name=entry.getKey();
			String val = req.getParameter(entry.getValue());
			try {
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);
				field.set(obj, val);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return obj;
	}
	
	public static void write(Writer wr,String val) {
		try {
			wr.write(val);
			wr.flush();
			wr.close();
			wr=null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void write(Writer wr,Object val) {
	
		if(val instanceof Collection<?>) {
			write(wr,new JSONArray((Collection<?>) val).toString());
		}else if(val instanceof String) {
			write(wr,val.toString());
		}else if(val instanceof Map<?,?>) {
			write(wr,new JSONObject((Map<?,?>) val).toString());
		}else {
			write(wr,new JSONObject(val).toString());
		}
	}
	
}
